package com.github.common.extend.demo.util.excel.convert;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.github.common.extend.demo.config.BaseEnum;
import com.github.common.extend.demo.config.json.BaseEnumSerialize;

/**
 * 使用easy-excel导出时支持{@link BaseEnumSerialize}
 * @author wangjj7
 * @date 2022/10/24
 * @description
 */
public class BaseEnumExcelPropertyConverter implements Converter<Object> {

    @Override
    public Class supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration)
    {
        throw new IllegalStateException("暂不支持加载");
    }

    @Override
    public WriteCellData<String> convertToExcelData(Object value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if (value != null){
            BaseEnumSerialize baseEnumSerialize = contentProperty.getField().getAnnotation(BaseEnumSerialize.class);
            if (baseEnumSerialize == null){
                throw new IllegalStateException("缺少@BaseEnumSerialize，无法获取描述信息");
            }

            Class<? extends BaseEnum> baseEnumClass = baseEnumSerialize.type();
            BaseEnum[] enumConstants = baseEnumClass.getEnumConstants();
            for (BaseEnum enumConstant : enumConstants) {
                if (value.equals(enumConstant.getCode())){
                    return new WriteCellData<>(enumConstant.getDesc());
                }
            }
        }

        return new WriteCellData<>("");
    }

}
